const app = getApp()
Page({
  data: {
    counting: false,//倒计时,
    view: 'front'
  },
  onLoad: function () {
    this.daojishi();//一进来就拍照倒计时
    this.ctx = wx.createCameraContext()//创建摄像头对象
  },
  //倒计时
  daojishi: function () {
    var that = this;
    if (!that.data.counting) {
      //开始倒计时5秒
      countDown(that, 5);
    }
  },
  switch1Change(e) {
    if (e.detail.value) {
      this.setData({ view: 'front' })
    } else {
      this.setData({ view: 'back' })
    }
  },
  //重新拍照上传
  rePhotoAndUpload: function () {
    wx.navigateTo({
      url: 'camera'
    })
  }
})
//倒计时函数 在page外
function countDown(that, count) {
  if (count == 0) {
    //等于0时拍照
    that.ctx.takePhoto({
      quality: 'high',
      success: (res) => {
        that.setData({
          src: res.tempImagePath
        })
        wx.showToast({
          title: '拍照完成',
        })
        var data = {
          staffId: app.globalData.staffId
        }
        console.info("开始比对照片");
        console.info("开始比对照片src", res.tempImagePath);
        var url = "faceCheck";
        //上传图片并比对
        app.func.reqUploadFile(data, url, res.tempImagePath, function (res) {
          console.log(res);
          if (!res) {
            wx.hideLoading();
            wx.showToast({
              title: '比对失败',
              duration: '5000'
            })
          }
          var resultData = JSON.parse(res.data);
          console.info("code", resultData.code);
          if (resultData.code == 0) {
            wx.hideLoading();
            console.info("scpre", resultData.score)
            var title = resultData.score;
            //取出相识度
            if (resultData.score > 50) {
              wx.navigateTo({ url: "../hand/hand" })
            } else {
              wx.showToast({
                title: "照片相似的为：" + title + "%,验证失败！",
                duration: 5000,
                icon: "none"
              });
            }
          } else {
            wx.hideLoading();
            console.info(res.data);
            var msg = resultData.msg;
            console.info(msg);
            wx.showToast({
              title: msg + "请您重新拍照",
              duration: 5000
            });
          }
        });
      }
    })
    that.setData({
      counting: false
    })
    return;
  }
  wx.showLoading({//加载时显示倒计时
    title: '拍照倒计时' + count + '秒',
  })

  setTimeout(function () {
    wx.hideLoading()
  }, 1000)
  that.setData({
    counting: true,
  })
  setTimeout(function () {
    count--;
    countDown(that, count);
  }, 1000);
}